/**
 * Copyright (C), 2015-2018, 北京译泰教育科技有限公司
 * FileName: ReflectionUtil
 * Author:   andy
 * Date:     18/1/28 上午2:02
 * Description: ${DESCRIPTION}
 * History:
 */
package org.smart4j.framework.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 反射工具类<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/1/28 上午2:02
 */
public class ReflectionUtil {

    private static final Logger LOG = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 创建实例
     */
    public static Object newInstance(Class<?> cls) {
        Object instance;
        try {
            instance = cls.newInstance();
        } catch (Exception e){
            LOG.error("new instance failure", e.getMessage());
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     * 调用方法
     */
    public static Object invokeMethod(Object obj, Method method, Object... args){
        Object result;
        try {
            method.setAccessible(true);
            result = method.invoke(obj, args);
        } catch (IllegalAccessException e) {
            LOG.error("invoke method failure", e.getMessage());
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            LOG.error("invoke method failure", e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 设置成员变量的值
     */
    public static void setField(Object obj, Field field, Object value){
        try {
            field.setAccessible(true);
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            LOG.error("set field failure", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
